/**
 * 品牌系列页入库达成率图表组件
 */
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import http from '@/axios/http'
import adaptivePx from '@/utils/adaptivePx'

const route = useRoute()
const series = ref(route.query.series)

const main = ref()
const warehousingChart = ref()
const warehousingInfo = ref()
let myChart = null

const date = new Date()
const lastYear = (date.getFullYear() - 1) + '年'
const thisYear = date.getFullYear() + '年'

async function getWarehousingChart() {
  await http.post('/series/getWarehousingChart', {
    series: series.value
  }).then(res => {
    warehousingChart.value = res.data
  }).catch(err => {
    console.log(err)
  })
}

async function getWarehousingInfo() {
  await http.post('/series/getWarehousingInfo', {
    series: series.value
  }).then(res => {
    warehousingInfo.value = res.data
  }).catch(err => {
    console.log(err)
  })
}

async function init() {
  myChart = echarts.init(main.value, null, { renderer: 'svg'})

  myChart.showLoading({
    // 显示的文本
    text: ' 加载中......',
    // 旋转的圆圈颜色
    color: '#8f00ff',
    // 文本的颜色
    textColor: '#ffffff',
    // 背景色
    maskColor: 'rgba(0, 0, 0, 0.2)', 
    // 字体大小。从 `v4.8.0` 开始支持。
    fontSize: adaptivePx(15),
    // 是否显示旋转动画（spinner）。从 `v4.8.0` 开始支持。
    showSpinner: true,
    // 旋转动画（spinner）的半径。从 `v4.8.0` 开始支持。
    spinnerRadius: adaptivePx(15),
    // 旋转动画（spinner）的线宽。从 `v4.8.0` 开始支持。
    lineWidth: adaptivePx(7),
    // 字体粗细。从 `v5.0.1` 开始支持。
    fontWeight: 'normal',
    // 字体风格。从 `v5.0.1` 开始支持。
    fontStyle: 'normal',
    // 字体系列。从 `v5.0.1` 开始支持。
    fontFamily: 'system-ui'
  })

  await getWarehousingChart()
  await getWarehousingInfo()

  let option = {
    title: {
      text: '标准秒值⭐',
      textStyle: {
        color: 'white',
        fontSize: adaptivePx(16),
        fontWeight: 'normal'
      },
      left: '2%',
      top: '2%'
    },
    color: ['#1e90ff', '#2fa8c3'],
    legend: {
      textStyle: {
        color: 'white',
        fontSize: adaptivePx(14),
        fontWeight: 'normal'
      },
      top: '2%',
      right: '2%',
      data: [lastYear, thisYear]
    },
    grid: {
      left: '3%',
      top: '27%',
      right: '5%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      axisLabel: {
        color: 'white',
        fontSize: adaptivePx(12),
        fontWeight: 'normal'
      },
      data: warehousingChart.value.month
    },
    yAxis: {
      axisLabel: {
        color: 'white',
        fontSize: adaptivePx(12),
        fontWeight: 'normal'
      },
      axisLine: {
        lineStyle: {
          type: 'solid'
        },
        show: true
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#666'
        },
        show: true
      }
    },
    series: [
      {
        name: lastYear,
        type: 'bar',
        data: warehousingChart.value.lastWarehousingChart,
        markPoint: {
          symbol: warehousingChart.value.lastWarehousingChart[warehousingChart.value.lastWarehousingChart.length - 1] > 0 ? 'pin' : 'none',
          symbolSize: adaptivePx(60),
          label: {
            color: 'white',
            fontSize: adaptivePx(12),
            fontWeight: 'normal'
          },
          data: [
            {
              name: 'Total',
              coord: [warehousingChart.value.lastWarehousingChart.length - 1, warehousingChart.value.lastWarehousingChart[warehousingChart.value.lastWarehousingChart.length - 1]],
              value: warehousingChart.value.lastWarehousingChart[warehousingChart.value.lastWarehousingChart.length - 1]
            }
          ]
        },
        barWidth: '15%'
      },
      {
        name: thisYear,
        type: 'bar',
        data: warehousingChart.value.thisWarehousingChart,
        markPoint: {
          symbol: warehousingChart.value.thisWarehousingChart[warehousingChart.value.thisWarehousingChart.length - 1] > 0 ? 'pin' : 'none',
          symbolSize: adaptivePx(60),
          label: {
            color: 'white',
            fontSize: adaptivePx(12),
            fontWeight: 'normal'
          },
          data: [
            {
              name: 'Total',
              coord: [warehousingChart.value.thisWarehousingChart.length - 1, warehousingChart.value.thisWarehousingChart[warehousingChart.value.thisWarehousingChart.length - 1]],
              value: warehousingChart.value.thisWarehousingChart[warehousingChart.value.thisWarehousingChart.length - 1]
            }
          ]
        },
        barWidth: '15%'
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        axis: 'x',
      },
      textStyle: {
        color: 'black',
        fontSize: adaptivePx(14),
        fontWeight: 'normal'
      },
      backgroundColor: 'rgba(171, 182, 212, 0.9)',
      borderWidth: 0,
      position: function (point, params, dom, rect, size) {
        return [point[0] + adaptivePx(20), point[1] - size.contentSize[1] * 0.5]
      },
      formatter: function (params) {
        let year = (new Date()).getFullYear()
        let month = warehousingInfo.value[params[0].name]
        let content = ''

        let hasThis = false
        let hasLast = false

        if (!month || month.length === 0) {
          return "暂无数据"
        }

        content += `
          <table style="text-align: center; font-weight: normal;">
            <thead>
              <tr>
                <th></th>
        `

        for (let item of month) {
          if (item.this_tot) {
            hasThis = true
          }
          if (item.last_tot) {
            hasLast = true
          }
        }

        if (hasThis) {
          content += `
                <th>&nbsp;${ year }年${ params[0].name === 'Total' ? '全年' : params[0].name + '月' }&nbsp;</th>
          `
        }

        if (hasLast) {
          content += `
                <th>&nbsp;${ year - 1 }年${ params[0].name === 'Total' ? '全年' : params[0].name + '月' }&nbsp;</th>
          `
        }

        if (hasThis && hasLast) {
          content += `
                <th>&nbsp;VS${ String(year - 1).substring(2) }&nbsp;</th>
          `
        }

        content += `
              </tr>
            </thead>
            <tbody>
        `

        for (let item of month) {
          if (item.factory === '合计' && month.length === 2) {
            continue
          }
          content += `
            <tr>
              <td style="text-align: left;">${ item.factory }</td>
          `
          if (hasThis) {
            content +=  `
              <td>${ item.this_tot.toLocaleString() }</td>
            `
          }
          if (hasLast) {
            content +=  `
              <td>${ item.last_tot.toLocaleString() }</td>
            `
          }
          if (hasThis && hasLast) {
            let diff = item.this_tot - item.last_tot
            if (diff > 0) {
              content += `
                <td style="color: blue;">+${ diff.toLocaleString() }</td>
              `
            } else {
              content += `
                <td style="color: red;">${ diff.toLocaleString() }</td>
              `
            }
          }
          content += `
              </tr>
          `
        }

        content += `
            </tbody>
          </table>
        `

        return content
      }
    }
  }

  myChart.setOption(option)

  myChart.on('legendselectchanged', () => {
    event.stopPropagation()
  })

  myChart.hideLoading()
}

function myChartResize() {
  if (myChart) {
    myChart.resize()
  }
}

onMounted(() => {
  init()
  
  window.addEventListener('resize', myChartResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', myChartResize)
})
</script>

<template>
  <div id="series-warehousing-chart" ref="main"></div>
</template>

<style lang="scss" scoped>
#series-warehousing-chart {
  width: 100%;
  height: 100%;
}
</style>